package com.extraty.question4;

/**
 * @author Created by Neil Wang
 * @version 1.0.0
 * @date 2021/9/7 2:07 下午
 */
public class Solution1 {
    public double findMedianSortedArrays(int[] nums1, int[] nums2) {
        int firstLength = nums1.length;
        int secondLength = nums2.length;
        if (firstLength > secondLength) return findMedianSortedArrays(nums2, nums1);
        int k = (firstLength + secondLength + 1) / 2;
        int left = 0;
        int right = firstLength;
        while (left < right) {
            int m1 = left + (right - left) / 2;
            if (nums1[m1] < nums2[k - m1 - 1]) left = m1 + 1;
            else right = m1;
        }
        int m1 = left;
        int m2 = k - left;
        int c1 = Math.max(m1 <= 0 ? Integer.MIN_VALUE : nums1[m1 - 1], m2 <= 0 ? Integer.MIN_VALUE : nums2[m2 - 1]);
        if (isSingle(firstLength, secondLength)) return c1;
        return (c1 + Math.min(m1 >= firstLength ? Integer.MAX_VALUE : nums1[m1],
                m2 >= secondLength ? Integer.MAX_VALUE : nums2[m2])) * 0.5;
    }

    private boolean isSingle(int firstLength, int secondLength) {
        return (firstLength + secondLength) % 2 == 1;
    }

}
